local ST = LibStub("AceAddon-3.0"):GetAddon("SurgeTrack", true)
local STLDB = ST:NewModule("SurgeTrack_LDB")
local LDB = LibStub("LibDataBroker-1.1", true)
local LDBIcon = LDB and LibStub("LibDBIcon-1.0", true)

function ST:LoadSTLDB()
 ST:EnableModule("SurgeTrack_LDB")
 ST:DisableModule("SurgeTrack_LDB")
end
function STLDB:OnEnable()
 STLDB:InitLDB()
end
function STLDB:InitLDB()
 ST.broker = {}
 ST.broker.name = "Broker_SurgeTrack"

 if LDB then
  ST.broker.obj = LDB:NewDataObject(ST.broker.name, {
   icon = ST.IMG,
   label = ST.NAME,
   text = ST.NAME,
   OnClick = function(clickedframe, button)
    if button == "MiddleButton" and ST:IsEnabled() then
     InterfaceOptionsFrame_OpenToCategory(ST.NAME)
    elseif button == "RightButton" then
     LibStub("AceConfigDialog-3.0"):Open(ST.NAME)
    elseif button == "LeftButton" then
     ST:Switch()
    end
   end,
   OnTooltipShow = function(tip)
    if not tip or not tip.AddLine then return end
    tip:AddLine(ST.NAME)
    for spellId,item in pairs(ST.active_item) do
     tip:AddLine(item.spellName)
     tip:AddLine(floor(item.timestamp + item.duration - GetTime()))
    end
   end,
  })
  if LDBIcon and not IsAddOnLoaded("Broker2FuBar") and not IsAddOnLoaded("FuBar") then
   LDBIcon:Register(ST.broker.name, ST.broker.obj, ST.db.profile.minimap)
  end
 end
end
function ST:LDBUpdate(spellIcon,spellName)
 if not ST.broker.obj then return end
 ST.broker.obj.icon = spellIcon
 ST.broker.obj.text = spellName
end
